package io.itit.ecp.admin.provide.selected;

import com.alibaba.fastjson.JSONObject;
import icu.mhb.mybatisplus.plugln.extend.Joins;
import io.itit.ecp.admin.provide.action.req.SceneCompanyQueryReq;
import io.itit.ecp.admin.server.entity.SceneCompanyEntity;
import io.itit.ecp.admin.server.entity.SceneRoomEntity;
import io.itit.grass.common.provide.action.resp.SelectedResp;
import io.itit.grass.common.server.selected.ISelected;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 公司选择器
 */
@Component
public class SceneCompanySelected implements ISelected<SelectedResp> {

    public static final String CODE = "SceneCompanySelected";

    @Override
    public String code() {
        return CODE;
    }

    @Override
    public List<SelectedResp> get(String param) {
        SceneCompanyQueryReq req = JSONObject.isValidObject(param) ? JSONObject.parseObject(param, SceneCompanyQueryReq.class) : new SceneCompanyQueryReq();
        return Joins.of(SceneCompanyEntity.class)
                .selectAll()
                .leftJoin(SceneRoomEntity.class, SceneRoomEntity::getSceneCompanyId, SceneCompanyEntity::getId)
                .eq(StringUtils.isNotEmpty(req.getSceneRoomId()), SceneRoomEntity::getId, req.getSceneRoomId())
                .eq(StringUtils.isNotEmpty(req.getSceneFloorId()), SceneRoomEntity::getSceneFloorId, req.getSceneFloorId())
                .eq(StringUtils.isNotEmpty(req.getSceneEdificeId()), SceneRoomEntity::getSceneEdificeId, req.getSceneEdificeId())
                .end()
                .eq(StringUtils.isNotEmpty(req.getSceneProjectId()), SceneCompanyEntity::getSceneProjectId, req.getSceneProjectId())
                .orderByAsc(SceneCompanyEntity::getCompanyName)
                .distinct()
                .joinList(SceneCompanyEntity.class)
                .stream()
                .map(t -> SelectedResp.builder().label(t.getCompanyName()).value(t.getId()).build())
                .collect(Collectors.toList());
    }
}
